﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using DevelopTool.Bll.CodeBlls;
using DevelopTool.Common;
using DevelopTool.Forms.BaseForms;
using DevelopTool.Model.CodeModels;
using Sunny.UI;

namespace DevelopTool.Forms.CodeForms
{
    public partial class CodeForm : BaseUIPage
    {

        private CodeBll codeBll;

        /// <summary>
        /// 当前代码对象
        /// </summary>
        private Code currentCode;


        public CodeForm(Code code)
        {
            InitializeComponent();

            currentCode = code;
            codeBll = new CodeBll();
        }


        private void CodeForm_Load(object sender,EventArgs e)
        {
            this.codeEditorMainCode.ContentText = currentCode.MainCodeText;
            this.codeEditorCustomCode.ContentText = currentCode.CustomCodeText;

            this.LoadListBoxReference(currentCode.LibraryReference,true);//加载程序集引用
        }


        /// <summary>
        /// 保存代码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiSymbolButtonSaveCode_Click(object sender,EventArgs e)
        {
            Code codeText = codeBll.GetById(currentCode.Id);
            codeText.MainCodeText = this.codeEditorMainCode.ContentText;
            codeText.CustomCodeText = this.codeEditorCustomCode.ContentText;
            codeBll.Save(codeText);
            this.ShowSuccessNotifier("代码保存成功");
        }


        /// <summary>
        /// 运行代码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiSymbolButtonRun_Click(object sender,EventArgs e)
        {
            if(string.IsNullOrWhiteSpace(this.codeEditorMainCode.ContentText))
            {
                this.ShowWarningNotifier("入口代码为空");
                return;
            }

            Code code = codeBll.GetById(currentCode.Id);
            var result = CSScriptHelper.ExecuteCode(this.codeEditorMainCode.ContentText,this.codeEditorCustomCode.ContentText,code.LibraryReference);
            this.codeEditorLog.ContentText = this.codeEditorLog.ContentText.Insert(0,result.Item2 + "\n");

        }

        /// <summary>
        /// 添加程序集
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiSymbolButtonAddReference_Click(object sender,EventArgs e)
        {
            using(OpenFileDialog dialog = new OpenFileDialog { Title = "添加程序集引用" })
            {
                dialog.Filter = "程序集|*.dll";
                dialog.Multiselect = true;
                if(dialog.ShowDialog() == DialogResult.OK)
                {
                    Code codeText = codeBll.GetById(currentCode.Id);

                    bool exists = false;
                    List<string> dllPaths = dialog.FileNames.ToList();
                    foreach(string dllPath in dllPaths)
                    {
                        if(codeText.LibraryReference.Exists(it => it == dllPath))//检查是否已引用程序集
                        {
                            this.ShowWarningDialog($"程序集{Path.GetFileName(dllPath)}已引用，请勿重复添加");
                            exists = true;
                            return;
                        }
                    }
                    if(exists) return;

                    codeText.LibraryReference.AddRange(dllPaths);//追加程序集
                    codeBll.Save(codeText);
                    this.ShowSuccessNotifier("程序集保存成功");
                    LoadListBoxReference(codeText.LibraryReference,false);
                }
            }

        }

        /// <summary>
        /// 加载程序集引用控件列表
        /// </summary>
        /// <param name="libraryReferenceList"></param>
        /// <param name="reload"></param>
        private void LoadListBoxReference(List<string> libraryReferenceList,bool reload = false)
        {
            uiSplitContainer1.Panel2Collapsed = libraryReferenceList.Count <= 0 ? true : false;

            if(reload) this.uiListBoxReference.Items.Clear();
            foreach(string libraryReference in libraryReferenceList)
            {
                this.uiListBoxReference.Items.Add(Path.GetFileName(libraryReference));
            }
        }


        /// <summary>
        /// 选择某一项程序集事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiListBoxReference_SelectedValueChanged(object sender,EventArgs e)
        {
            if(uiListBoxReference.SelectedIndex < 0) return;

            Code codeText = codeBll.GetById(currentCode.Id);
            var libraryReference = codeText.LibraryReference[uiListBoxReference.SelectedIndex];

            this.rTxtLibraryInfo.Text = libraryReference;
        }

        /// <summary>
        /// 程序集引用控件列表右键菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiListBoxReference_MouseDown(object sender,MouseEventArgs e)
        {
            if(e.Button == MouseButtons.Right && this.uiListBoxReference.SelectedItem != null)
            {
                this.uiListBoxReference.ContextMenuStrip = this.ContextMenuStripReference;
            }
        }

        private void 删除程序集引用ToolStripMenuItem_Click(object sender,EventArgs e)
        {
            if(this.uiListBoxReference.SelectedItem == null) return;
            var libraryReferenceName = this.uiListBoxReference.SelectedItem.ToString();

            if(this.ShowAskDialog($"{GlobalData.AppName_zh}-重要提示", $"是否确定删除程序集引用【{libraryReferenceName}】？", UIStyle.Orange))
            {
                Code codeText = codeBll.GetById(currentCode.Id);
                codeText.LibraryReference.RemoveAll(it => Path.GetFileName(it).Equals(libraryReferenceName));
                codeBll.Save(codeText);

                this.ShowSuccessNotifier($"{libraryReferenceName}已删除");
                LoadListBoxReference(codeText.LibraryReference,true);
                this.rTxtLibraryInfo.Text = "";
            }
        }

        private void 清空日志ToolStripMenuItem_Click(object sender,EventArgs e)
        {
            this.codeEditorLog.ClearContent();
        }

        private void rTxtLog_MouseDown(object sender,MouseEventArgs e)
        {
            if(e.Button == MouseButtons.Right)
            {
                this.codeEditorLog.ContextMenuStrip = this.ContextMenuStripLog;
            }
        }
    }
}
